package com.ys.service.storage.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.AddDto;
import com.ys.dto.EditDto;
import com.ys.entity.base.CheckByGrid;
import com.ys.entity.business.TbBaseInfo;
import com.ys.entity.flow.YspModel;
import com.ys.entity.storage.*;
import com.ys.entity.sys.*;
import com.ys.enume.base.TransactionTypeEnum;
import com.ys.enume.finance.TcwFinancialTransactionFlowEnum;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.enume.storage.TccLogisticsComprehensiveEnum;
import com.ys.mapper.storage.*;
import com.ys.service.business.TcwAccountDetailedForCompanyService;
import com.ys.service.finance.TcwAccountCountForCompanyService;
import com.ys.service.finance.TcwFinancialTransactionFlowService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.storage.TccLogisticsPaymentFeeService;
import com.ys.util.CheckUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: xjx
 * @CreateTime: 2025-03-04
 * @Description: 物流付款单（物流费
 * @Version: 1.5
 */
@Service("tccLogisticsPaymentFeeService")
public class TccLogisticsPaymentFeeServiceImpl implements TccLogisticsPaymentFeeService {
    private static final Logger logger = LoggerFactory.getLogger(TccLogisticsPaymentFeeServiceImpl.class);

    @Autowired
    private TccLogisticsPaymentFeeMapper tccLogisticsPaymentFeeMapper;

    @Autowired
    private TccLogisticsPaymentFeeItemMapper tccLogisticsPaymentFeeItemMapper;

    @Autowired
    private YspTaskService yspTaskService;

    @Autowired
    private TcwAccountDetailedForCompanyService tcwAccountDetailedForCompanyService;

    @Autowired
    private TcwFinancialTransactionFlowService tcwFinancialTransactionFlowService;

    @Autowired
    private TccLogisticsComprehensiveMapper tccLogisticsComprehensiveMapper;

    @Autowired
    private CheckUtil checkUtil;

    @Autowired
    private StorageMapper storageMapper;


    private final Long GRID = 90L;


    /**
     * 新增
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R add(Map<String, Object> params, Long menuId) throws Exception {
        logger.info("物流付款单（物流费）新增传参："+params);

        //参数验证
        String errorBack = checkParams(params, menuId);
        if(errorBack!=null && !"".equals(errorBack)){
            return R.error(errorBack);
        }
        TccLogisticsPaymentFee entity = JSON.parseObject(JSON.toJSONString(params), TccLogisticsPaymentFee.class);
        entity.setStatus(1);//状态
        entity.setEffectStock(0);//审批状态

        //获取制单人信息
        TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setStatus(1).queryFirst();
        if(tsUserChange!=null){
            entity.setCreateChangeId(tsUserChange.getId());//制单人变更信息
        }else {
            return R.error("未查询到制单人信息！");
        }

        //保存列表信息
        R saveItemRes = saveItem(params,entity);
        if(saveItemRes.getCode()==1){
            return saveItemRes;
        }

        //新增
        tccLogisticsPaymentFeeMapper.insert(entity);

        YsMenu ysMenu = new YsMenu().setId(menuId).queryFirst();
        if (ysMenu.getFlowModelId().longValue() != 0L) {
            YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
            String codeModel = yspModel.getCode();
            String createUserId = ShiroUtils.getUserId();
            yspTaskService.init(codeModel, entity.getBid(), createUserId);
        }

        return R.ok(AddDto.gotoEdit("/web/storage/tccLogisticsPaymentFee/toEdit?bid=" + entity.getBid()));
    }


    /**
     * 修改
     * @param params
     * @param menuId
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R toEdit(Map<String, Object> params, Long menuId) throws Exception {
        logger.info("物流付款单（物流费）修改传参："+params);
        //参数验证
        String errorBack = checkParams(params, menuId);
        if(errorBack!=null && !"".equals(errorBack)){
            return R.error(errorBack);
        }
        TccLogisticsPaymentFee entity = JSON.parseObject(JSON.toJSONString(params), TccLogisticsPaymentFee.class);
        // 验证状态
        YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
        if (ysProcInst == null) {
            return R.error("审批数据不存在，无法编辑");
        } else if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.INIT.value) {
            return R.error("已流转，无法编辑");
        }

        //保存列表信息
        R saveItemRes = saveItem(params,entity);
        if(saveItemRes.getCode()==1){
            return saveItemRes;
        }

        //修改
        tccLogisticsPaymentFeeMapper.update(entity);

        return R.ok();
    }



    //保存子列表信息
    public R saveItem(Map<String, Object> params, TccLogisticsPaymentFee entity) throws Exception{
        //保存列表信息
        List<Map<String, Object>> subDataList;
        if(params.get("subData")!=null){
            JSONArray subData = JSON.parseArray(params.get("subData").toString());
            CheckByGrid checkByGrid = checkParamsByGrid(subData,GRID,params,entity.getBid());
            if(checkUtil.isNotNullByObject(checkByGrid.getErrMsg())){
                return R.error(checkByGrid.getErrMsg());
            }
            subDataList = checkByGrid.getSubDataList();
        }else {
            return R.error("列表信息为空！");
        }

        for(Map<String, Object> item:subDataList){
            String logInvoiceNo = item.get("logInvoiceNo").toString();
            //修改回：服务商物流金额（支付）
            TccLogisticsComprehensive tccLogisticsComprehensive = getInfoByOne(logInvoiceNo);
            if(tccLogisticsComprehensive!=null && tccLogisticsComprehensive.getStatus()!=null){
                TccLogisticsPaymentFeeItem tccLogisticsPaymentFeeItem = new TccLogisticsPaymentFeeItem()
                        .setPbid(entity.getBid())
                        .setLogInvoiceNo(logInvoiceNo)
                        .queryFirst();
                //BigDecimal spLogsticsFee = tccLogisticsComprehensive.getSpLogsticsFee();//服务商物流费用（导入）
                BigDecimal logSpAmount = tccLogisticsComprehensive.getLogSpAmount();//服务商物流金额（支付）
                if(tccLogisticsPaymentFeeItem!=null && tccLogisticsPaymentFeeItem.getId()!=null){
                    //保存过：服务商物流金额（支付）-  已保存的金额
                    logSpAmount = logSpAmount.subtract(tccLogisticsPaymentFeeItem.getPayAmount());
                }
                //修改支付金额
                updateAmount(tccLogisticsComprehensive, logSpAmount);
            }else {
                throw new RuntimeException("物流表信息获取有误");
            }
        }

        //删除子表信息
        storageMapper.delTccLogisticsPaymentFeeItemByBid(entity.getBid());

        //再新增
        //新增子件信息
        for (Map<String, Object> item:subDataList) {
            TccLogisticsPaymentFeeItem itemInfo = JSON.parseObject(JSON.toJSONString(item), TccLogisticsPaymentFeeItem.class);
            itemInfo.setStatus(1);
            itemInfo.setPbid(entity.getBid());
            //新增
            tccLogisticsPaymentFeeItemMapper.insert(itemInfo);

            //修改：服务商物流金额（支付）
            TccLogisticsComprehensive tccLogisticsComprehensive = getInfoByOne(itemInfo.getLogInvoiceNo());
            if(tccLogisticsComprehensive!=null && tccLogisticsComprehensive.getStatus()!=null){
                BigDecimal logSpAmount = tccLogisticsComprehensive.getLogSpAmount();//服务商物流金额（支付）
                logSpAmount = logSpAmount.add(itemInfo.getPayAmount());
                //修改支付金额
                updateAmount(tccLogisticsComprehensive, logSpAmount);
            }else{
                throw new RuntimeException("物流表信息获取有误");
            }
        }

        return R.ok();
    }


    //获取物流数据
    public TccLogisticsComprehensive getInfoByOne(String logInvoiceNo)throws Exception{
        return  new TccLogisticsComprehensive()
                .setLogInvoiceNo(logInvoiceNo)
                .setIsFirstByInvoice(1)
                .queryFirst();
    }

    //修改支付金额
    public void updateAmount(TccLogisticsComprehensive infoByOne, BigDecimal amount)throws Exception{
        //查询发票下的所有FBA信息
        List<TccLogisticsComprehensive> logList = new TccLogisticsComprehensive()
                .setLogInvoiceNo(infoByOne.getLogInvoiceNo())
                .queryList();

        for(TccLogisticsComprehensive infoItem:logList){
            infoItem.setLogSpAmount(amount);
            tccLogisticsComprehensiveMapper.update(infoItem);
        }

    }



    /**
     * 删除
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R deleteTrue( Long id) throws Exception {

        if (id == null) {
            return R.error("ID不能为空");
        }

        TccLogisticsPaymentFee entity = new TccLogisticsPaymentFee().setId(id).queryFirst();
        if (entity == null){
            return R.error("单据不存在,请核实后再操作!");
        }
        if (entity.getEffectStock() == FlowEnum.EffectStock.EFFECTED.value) {
            return R.error("已生效数据无法删除");
        }

        //修改回：服务商物流金额（支付）
        List<TccLogisticsPaymentFeeItem> itemList = new TccLogisticsPaymentFeeItem().setPbid(entity.getBid()).queryList();
        for(TccLogisticsPaymentFeeItem item:itemList){
            String logInvoiceNo = item.getLogInvoiceNo();
            TccLogisticsComprehensive tccLogisticsComprehensive = getInfoByOne(logInvoiceNo);
            if(tccLogisticsComprehensive!=null && tccLogisticsComprehensive.getStatus()!=null){
                TccLogisticsPaymentFeeItem tccLogisticsPaymentFeeItem = new TccLogisticsPaymentFeeItem()
                        .setPbid(entity.getBid())
                        .setLogInvoiceNo(logInvoiceNo)
                        .queryFirst();
                //BigDecimal spLogsticsFee = tccLogisticsComprehensive.getSpLogsticsFee();//服务商物流费用（导入）
                BigDecimal logSpAmount = tccLogisticsComprehensive.getLogSpAmount();//服务商物流金额（支付）
                if(tccLogisticsPaymentFeeItem!=null && tccLogisticsPaymentFeeItem.getId()!=null){
                    //保存过：服务商物流金额（支付）-  已保存的金额
                    logSpAmount = logSpAmount.subtract(tccLogisticsPaymentFeeItem.getPayAmount());
                }
                //修改支付金额
                updateAmount(tccLogisticsComprehensive, logSpAmount);
            }else {
                throw new RuntimeException("物流表信息获取有误");
            }
        }

        //删除子表数据
        storageMapper.delTccLogisticsPaymentFeeItemByBid(entity.getBid());

        String loginUserId = ShiroUtils.getUserId();
        yspTaskService.flowDelete(entity.getBid(), loginUserId);
        return R.ok(EditDto.closeAndReload());
    }


    /**
     * 流转通过
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R flowPass(String bid,String loginUserId) throws Exception {

        TccLogisticsPaymentFee entity = new TccLogisticsPaymentFee().setBid(bid).queryFirst();
        if (entity == null){
            return R.error("单据不存在,请核实后再操作!");
        }
        Flow f = yspTaskService.flowPass(bid, loginUserId);
        if (f.getCode() == Flow.Code.FAILED.value) {
            return R.error(f.getMsg());
        } else {
            if (f.getState() == Flow.State.FINISH.value) {
                return flowFinish(entity);
            }
            return R.ok();
        }
    }





    /**
     * 流转结束
     */
    public R flowFinish(TccLogisticsPaymentFee entity) throws Exception {
        Date theDate = new Date();
        //******* 1、对公支付 =》 财务流水 *******
        if(entity.getIsPublicPay()==1){
            String transactionTypeStr = TransactionTypeEnum.BusinessType.WLFW_TCYF.name;
            TbBaseInfo transactionType = tcwFinancialTransactionFlowService.getTransactionType(transactionTypeStr);
            if(transactionType==null || transactionType.getId()==null){
                throw new IllegalArgumentException(transactionTypeStr+"未维护");
            }

            //新增财务交易流水
            R res = tcwFinancialTransactionFlowService.add(
                    true,
                    entity.getCompanyBankInfoId(),//公司银行账户管理表id（TB_CompanyBankInfo）
                    transactionType.getBid(),//业务交易类型bid（TB_BaseInfo）
                    entity.getBankAccountName(),//对方账户名称
                    entity.getOpeningBank(),//对方账户开户行
                    entity.getAccountNumber(),//对方银行账户编码
                    BigDecimal.ZERO.subtract(entity.getTotalAmount()),//交易金额
                    entity.getCreateTime(),//交易发生时间
                    theDate,//交易审核时间
                    theDate,//记账时间
                    "物流付款单："+entity.getBid()+"，"+entity.getTotalAmount(),//备注
                    TcwFinancialTransactionFlowEnum.FromType.TCC_LogisticsPaymentFee.value,//来源表单类型(见枚举类：TcwFinancialTransactionFlowEnum)
                    entity.getId()//来源表单id
            );

            if(res.getCode().equals(R.Code.FAILED.value)){//失败
                logger.info("新增财务交易流水失败:"+res.getMsg());
                throw new IllegalArgumentException(res.getMsg());
            }

            //业务支出流水
            //划出流水
            R resOut = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
                    "GS0899","物流部（中间账户）",
                    entity.getProviderBid(), entity.getAbbreviation(),
                    TransactionTypeEnum.BusinessType.WLFW_TCYF.name,
                    BigDecimal.ZERO.subtract(entity.getTotalAmount()),//交易金额
                    entity.getCreateTime(),
                    theDate,
                    "物流付款单："+entity.getBid()+"，"+entity.getTotalAmount(),//备注
                    entity.getBid(),
                    theDate
            );
            if(resOut.getCode().equals(R.Code.FAILED.value)){//失败
                logger.info("新增业务交易流水失败:"+resOut.getMsg());
                throw new IllegalArgumentException(resOut.getMsg());
            }
        }


        List<TccLogisticsPaymentFeeItem> itemList = new TccLogisticsPaymentFeeItem().setPbid(entity.getBid()).queryList();
        //List<TccLogisticsComprehensive> logList = new ArrayList<>();

        for(TccLogisticsPaymentFeeItem item:itemList){
            TccLogisticsComprehensive logItem = new TccLogisticsComprehensive()
                    .setLogInvoiceNo(item.getLogInvoiceNo())
                    .setIsFirstByInvoice(1)
                    .queryFirst();

            //TccLogisticsComprehensive logItem = logList.stream().filter(e->e.getLogInvoiceNo().equals(item.getLogInvoiceNo())).collect(Collectors.toList()).get(0);
            //如果物流导入 = 支付
            if(logItem.getSpLogsticsFee().compareTo(logItem.getLogSpAmount())==0){
                //如果除了本单之外的单据都已流转完成
                int hasOtherData = new TccLogisticsPaymentFeeItem()
                        .setLogInvoiceNo(logItem.getLogInvoiceNo())
                        .addLeftJoin("TCC_LogisticsPaymentTariff B ON A.Pbid = B.Bid")
                        .where("B.EffectStock = 0 AND A.Id !="+item.getId())
                        .count();
                if(hasOtherData<=0){

                    //******* 2、业务流水 *******

                    //logList.add(logItem);
                    TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(logItem.getFbaPlanBid()).queryFirst();
                    //物流发票费用（总）-服务商物流费用（导入）
                    BigDecimal amount = logItem.getLogInvoiceCost().subtract(logItem.getSpLogsticsFee());

                    if(amount.compareTo(BigDecimal.ZERO)>0){
                        String remark = "付款平账，物流付款单（"+amount+"）"+entity.getBid()+"，物流发票号："+logItem.getLogInvoiceNo()
                                +"，FBA发货单："+logItem.getFbaDeliverBid()
                                +"，FBA号："+logItem.getFbaNo();

                        //划出流水
                        R resOut = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
                                tccFbaPlan.getVgsbm(), tccFbaPlan.getVgsJc(),
                                "GS0899","物流部（中间账户）",
                                TransactionTypeEnum.BusinessType.WLFW_GSF.name,
                                BigDecimal.ZERO.subtract(amount),
                                item.getCreateTime(),
                                theDate,
                                remark,
                                entity.getBid(),
                                theDate
                        );
                        if(resOut.getCode().equals(R.Code.FAILED.value)){//失败
                            logger.info("新增业务交易流水失败:"+resOut.getMsg());
                            throw new IllegalArgumentException(resOut.getMsg());
                        }
                        //划入流水
                        R resIn = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
                                "GS0899","物流部（中间账户）",
                                tccFbaPlan.getVgsbm(), tccFbaPlan.getVgsJc(),
                                TransactionTypeEnum.BusinessType.WLFW_GSF.name,
                                amount,
                                item.getCreateTime(),
                                theDate,
                                remark,
                                entity.getBid(),
                                theDate
                        );
                        if(resIn.getCode().equals(R.Code.FAILED.value)){//失败
                            logger.info("新增业务交易流水失败:"+resIn.getMsg());
                            throw new IllegalArgumentException(resIn.getMsg());
                        }
                    }

                    //******* 3、修改物流付款状态 *******
                    //查询发票下的所有FBA信息
                    List<TccLogisticsComprehensive> logListByLogInvoiceNo = new TccLogisticsComprehensive()
                            .setLogInvoiceNo(logItem.getLogInvoiceNo())
                            .queryList();
                    for(TccLogisticsComprehensive infoItem:logListByLogInvoiceNo){
                        logItem.setLogPayStatusZf(TccLogisticsComprehensiveEnum.LogPayStatusZf.COMPLETE.value);
                        //修改物流订单对账说明
                        if(checkUtil.isNotNullByObject(logItem.getLogOrderlDesDz())){
                            logItem.setLogOrderlDesDz(logItem.getLogOrderlDesDz());
                        }
                        tccLogisticsComprehensiveMapper.update(infoItem);
                    }

                }
            }
        }

        return R.ok();
    }


    /**
     * 参数验证
     */
    public String checkParams(Map<String, Object> params, Long menuId) throws Exception {
        //获取pc字段数据
        List<YsCol> listField = new YsCol()
                .where("A.MenuId = "+menuId)
                .setOrderby("A.SortNo ASC")
                .queryList();
        //验证必填字段的非空；其他字段的长度限制、类型
        String backMsg = checkUtil.checkTableColLengthAndDataType("TCC_LogisticsPaymentFee",listField,params,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);

        return backMsg;
    }


    /**
     * 子表参数验证
     */
    public CheckByGrid checkParamsByGrid(JSONArray subDataArray, Long gridId, Map<String, Object> params,String bid) throws Exception {
        CheckByGrid checkByGrid = new CheckByGrid();
        //获取pc字段数据
        List<YsGridCol> listField = new YsGridCol()
                .setGridId(gridId)
                .setOrderby("A.SortNo ASC")
                .queryList();
        String backMsg = "";
        List<Map<String, Object>> subDataList = new ArrayList<>();

        if(subDataArray!=null && subDataArray.size()>0){
            for (int i = 0; i < subDataArray.size(); i++) {
                JSONObject jsonObject = subDataArray.getJSONObject(i);
                Map<String, Object> paramsNewByRecord = new HashMap<>();
                for (String key : jsonObject.keySet()) {
                    paramsNewByRecord.put(key, jsonObject.get(key));
                }
                subDataList.add(paramsNewByRecord);
            }
            //验证
            for(int i = 0;i<subDataList.size();i++){
                String backMsgByRow = "";
                Map<String, Object> subData = subDataList.get(i);
                //验证必填字段的非空；其他字段的长度限制、类型
                backMsgByRow += checkUtil.checkTableColLengthAndDataTypeByGrid(
                        "TCC_LogisticsPaymentFeeItem",
                        listField,
                        subData,
                        ysColItem->
                                ysColItem.getCode().equals("payAmount")//服务商关税本次付款金额
                                        || ysColItem.getCode().equals("logInvoiceNo")//物流发票号

                );
                if(checkUtil.isNotNullByObject(subData.get("payAmount"))){//本次付款金额，必须是正数
                    if(!checkUtil.isNumber(subData.get("payAmount").toString())){
                        backMsgByRow += "服务商关税本次付款金额应为数字；";
                    }else {
                        if(new BigDecimal(subData.get("payAmount").toString()).compareTo(BigDecimal.ZERO)<=0){
                            backMsgByRow += "服务商关税本次付款金额应≥0；";
                        }
                    }
                }


                //金额判断  &&  对账说明填入=》物流订单对账状态=》亏损=》必填
                if(checkUtil.isNotNullByObject(subData.get("logInvoiceNo"))){
                    String logInvoiceNo = subData.get("logInvoiceNo").toString();
                    TccLogisticsComprehensive tccLogisticsComprehensive = new TccLogisticsComprehensive()
                            .setLogInvoiceNo(logInvoiceNo)
                            .setIsFirstByInvoice(1)
                            .queryFirst();

                    if(tccLogisticsComprehensive==null || tccLogisticsComprehensive.getStatus()==null){
                        backMsgByRow += "物流表信息获取有误；";
                    }else {
                        //金额判断
                        TccLogisticsPaymentTariffItem tccLogisticsPaymentFeeItem = new TccLogisticsPaymentTariffItem()
                                .setPbid(bid)
                                .setLogInvoiceNo(logInvoiceNo)
                                .queryFirst();

                        BigDecimal spLogsticsFee = tccLogisticsComprehensive.getSpLogsticsFee();//服务商物流费用（导入）
                        BigDecimal logSpAmount = tccLogisticsComprehensive.getLogSpAmount();//服务商物流金额（支付）
                        if(tccLogisticsPaymentFeeItem!=null && tccLogisticsPaymentFeeItem.getId()!=null){
                            //保存过：服务商关税金额（支付）-  已保存的金额
                            logSpAmount = logSpAmount.subtract(tccLogisticsPaymentFeeItem.getPayAmount());
                        }
                        BigDecimal thisPayAmount = new BigDecimal(subData.get("payAmount").toString());
                        if((logSpAmount.add(thisPayAmount)).compareTo(spLogsticsFee)>0){
                            backMsgByRow += "服务商物流金额（支付）不能超过 服务商物流金额（导入）；";
                        }
                        //对账说明填入=》物流订单对账状态=》亏损=》必填
                        if(tccLogisticsComprehensive.getLogOrderStatusDz()!=null && tccLogisticsComprehensive.getLogOrderStatusDz().equals(TccLogisticsComprehensiveEnum.LogOrderStatusDz.DEFICIT.value)){
                            if(checkUtil.isNullByObject(subData.get("logOrderlDesDz"))){
                                backMsgByRow += "物流订单对账亏损，请填写对账说明；";
                            }
                        }
                    }
                }

                if(checkUtil.isNotNullByObject(backMsgByRow)){
                    backMsg += "列表第" + (i+1) + "行，" + backMsgByRow;
                }
            }
        }else{
            backMsg = "列表信息为空";
        }
        checkByGrid.setErrMsg(backMsg);
        checkByGrid.setSubDataList(subDataList);

        return checkByGrid;
    }




    //获取子列表数据
    @Override
    public List<Map<String,Object>> getItemList(String bid)throws Exception {
        return new TccLogisticsPaymentFeeItem()
                .setPbid(bid)
                //物流表id（TCC_LogisticsComprehensive）
                //本次物流付款金额
                //物流订单对账说明 logOrderlDesDz
                .addLeftJoin("TCC_LogisticsComprehensive SB ON SB.LogInvoiceNo = A.LogInvoiceNo")//物流信息表
                .addField("SB.FbaNo AS fbaNo") //FBA编号
                .addField("SB.SpOrderBid AS spOrderBid") // 服务商订单号

                .addField("SB.SpLogsticsFee AS spLogsticsFee")//        服务商物流费用（导入）
                .addField("SB.LogSpAmount AS logSpAmount")//        服务商物流金额（支付）
                .addField("SB.LogOrderProfitDz AS logOrderProfitDz")//        物流订单利润（对账）
                .addField("SB.LogServiceProfitDz AS logServiceProfitDz")//        物流服务利润（对账）
                .addField("SB.LogOrderMarginDz AS logOrderMarginDz")//        物流订单利润率（对账）
                .addField("SB.LogServiceMarginDz AS logServiceMarginDz")//        物流服务利润率（对账）
                .addField("SB.LogOrderStatusDz AS logOrderStatusDz")//        物流订单对账状态
                .addField("CASE " +
                        "WHEN SB.LogOrderStatusDz = 0 THEN '' " +
                        "WHEN SB.LogOrderStatusDz = 1 THEN '盈利' " +
                        "WHEN SB.LogOrderStatusDz = 2 THEN '低利润' " +
                        "WHEN SB.LogOrderStatusDz = 3 THEN '亏损' " +
                        " ELSE '' END logOrderStatusDzTxt")

                .addField("SB.LogInvoiceCost AS logInvoiceCost")//        物流发票费用（总）
                .addField("SB.LogInvoiceSalesFee AS logInvoiceSalesFee")//        物流销售费用（总）
                .addField("SB.LogChannelName AS logChannelName")//        物流渠道名称
                .addField("SB.FbaDeliverBid AS fbaDeliverBid")//                FBA发货单号
                .addField("SB.FbaBoxUpBid AS fbaBoxUpBid")//        FBA装箱单号
                .addField("SB.FbaPlanBid AS fbaPlanBid")//        FBA计划单号

                .addLeftJoin("TCC_FbaPlan SC ON SC.Bid = SB.FbaPlanBid")//FBA计划
                .addField("SC.DeliverState AS deliverState")//               发货计划（1按SKU自动发货，0按箱自动发货）
                .addField("CASE WHEN SC.DeliverState = 1 THEN '按SKU自动发货'  ELSE '按箱自动发货' END deliverStateTxt")// 发货计划（1按SKU自动发货，0按箱自动发货）

                .addField("SC.Vgsbm AS vgsbm")//        运营公司编码
                .addField("SC.VgsJc AS vgsJc")//                运营公司简称
                .addField("SC.DeclarationState AS declarationState")//                是否报关
                .addField("CASE WHEN SC.DeclarationState = 1 THEN '是'  ELSE '否' END declarationStateTxt")// 是否报关


                .addField("SC.ShopName AS shopName")//                网店名称

                .addLeftJoin("TCC_FbaDeliverItem SD ON SD.Id = SB.FbaDeliverItemId")//FBA发货单号详情id（TCC_FbaDeliverItem）
                .addLeftJoin("TCC_FbaBoxUpInfo SE ON SE.Id = SD.FbaBoxUpInfoId")//装箱单FBA信息
                .addField("SE.FbaWarehouse AS fbaWarehouse")//        FBA仓库
                .addField("SE.FbaTrackNo AS fbaTrackNo")//        FBA追踪编号

                .addLeftJoin("TCC_LogisticsChannelDetail SF ON SF.LogInvoiceNo = SB.LogInvoiceNo")//物流渠道详情表
                .addField("SF.LogsticsWay AS logsticsWay")// 物流服务名称

                // 制单人


                .where("SB.IsFirstByInvoice = 1")//是否是同一发票中的第一条（0否1是）
                .queryMap();

    }





}
